package com.zw.commons.log.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.zw.api.LogFeignClient;
import com.zw.commons.log.annotation.Log;
import com.zw.commons.utlis.IpUtil;
import com.zw.commons.utlis.JwtHelper;
import com.zw.object.system.SysOperLog;
import com.zw.object.vo.OperLogUpdate;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Aspect
@Component
@EnableFeignClients(basePackages = {"com.zw.api"})
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);


    private static ConcurrentHashMap<String, String> ids = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String, SysOperLog> sysOperLogMap = new ConcurrentHashMap<>();

    @Autowired
    private LogFeignClient feignClient;

    @Before("@annotation(log)")
    public void doBefore(JoinPoint joinPoint, Log log) {
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
    }

    @Around("@annotation(controllerLog)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Log controllerLog) {
        handleLog(proceedingJoinPoint, controllerLog);
        Object res = null;
        try {
            res = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return res;
    }

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String key = request.getRequestURI() + request.getSession().getId() + argsArrayToString(joinPoint.getArgs());
        String id = ids.get(key);
        String result = JSON.toJSONString(jsonResult);
        log.info("保存日志后置信息{}", result);
        OperLogUpdate operLogUpdate = new OperLogUpdate();
        operLogUpdate.setId(id);
        operLogUpdate.setJsonResult(result);
        feignClient.updateOperLog(operLogUpdate);

        // 删除存储的临时信息，避免内存泄露
        sysOperLogMap.remove(key);
        ids.remove(key);
    }

    // 如果发生错误则删除hashMap存储的临时信息，避免内存泄露
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Throwable e) {
        log.error("存储日志错误：{}", e.getMessage());
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String key = request.getRequestURI() + request.getSession().getId() + argsArrayToString(joinPoint.getArgs());
        sysOperLogMap.remove(key);
        ids.remove(key);
    }

    protected void handleLog(ProceedingJoinPoint joinPoint, Log controllerLog) {
        try {
            Object[] args = joinPoint.getArgs();
            if (ArrayUtils.isNotEmpty(args)) {
                List<Object> logArgs = Arrays.stream(args).filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof MultipartFile)))
                        .collect(Collectors.toList());
                log.info("处理保存日志  : {}", JSON.toJSONString(logArgs));
            } else {
                log.info("处理保存日志  : null");
            }
//            log.info("处理保存日志：{}", JSON.toJSONString(joinPoint.getArgs()));
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();

            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            //状态
            operLog.setStatus(1);

            // 请求的地址
            String ip = IpUtil.getIpAddress(request);//IpUtil.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            operLog.setOperUrl(request.getRequestURI());

            String token = request.getHeader("token");
            String userName = JwtHelper.getUsername(token);
            operLog.setOperName(userName);
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");

            // 设置请求方式
            operLog.setRequestMethod(request.getMethod());

            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog);

            // 操作日志保存数据库
            String id = feignClient.AsyncOperLogSave(operLog);
            operLog.setId(id);
            String key = request.getRequestURI() + request.getSession().getId() + argsArrayToString(joinPoint.getArgs());
            // 本地保存ID和信息
            if (id != null) {
                sysOperLogMap.put(key, operLog);
                ids.put(key, id);
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().name());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().name());
        // 是否需要保存request，参数和值
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(params);
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!StringUtils.isEmpty(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
